package org.example.network.demo4;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.SneakyThrows;
import org.example.network.demo2.client.ClientInboundHandler;

/**
 * @author Gong.Yang
 * 演示LengthFieldBasedFrameDecoder和LengthFieldPrepender
 */
public class Client {

    @SneakyThrows
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup(1))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        //出站
                        pipeline.addLast(new LengthFieldPrepender(4));

                        //入
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
                        pipeline.addLast(new ClientInboundHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8848).sync();
        Channel channel = channelFuture.channel();
        for (int i = 0; i < 100; i++) {
            byte[] message = new Message(i, "name" + i, i % 20).toString().getBytes();
            ByteBuf byteBuf = channel.alloc().buffer(message.length).writeBytes(message);
            channel.writeAndFlush(byteBuf);
        }
        channel.closeFuture().sync();
    }
}
